package com.hzncc.scaffold.controller.Rear.teachingClassroom.QuestionBank;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hzncc.scaffold.core.ResultT;
import com.hzncc.scaffold.entity.Bo.QuestionReaderBo;
import com.hzncc.scaffold.entity.Other.Question;
import com.hzncc.scaffold.entity.Other.Questionlib;
import com.hzncc.scaffold.entity.Vo.DeleteQuestionVo;
import com.hzncc.scaffold.entity.Vo.TrainingClassListVo;
import com.hzncc.scaffold.entity.Vo.UpdateQuestionVo;
import com.hzncc.scaffold.service.QuestionService;
import com.hzncc.scaffold.service.QuestionlibService;
import com.hzncc.scaffold.utils.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: DrunkBear
 * @Date: 2022-06-21 11:39
 * @Description: null
 */
@RequestMapping("/manage/question")
@Api(tags = "后台接口-题目")
@RestController
public class QuestionController {

    @Autowired
    QuestionService questionService;

    @Autowired
    QuestionlibService questionlibService;

    @PostMapping("/add")
    @ApiOperation("为题库新增题目")
    public ResultT add(@RequestBody Question question) {
        ResultT resultT = questionService.addQuestion(question);
        return resultT;
    }

    @PostMapping("/delete")
    @ApiOperation("删除题库中题目")
    public ResultT deleteQuestion(@RequestBody Map<String,Object> deleteQuestionVo) {

        List<Integer> questionId = new ArrayList<>();

        Object questionIdObj = deleteQuestionVo.get("questionId");
        Object questionLibIdObj = deleteQuestionVo.get("questionLibId");
        if(questionIdObj instanceof  Integer){
            questionId.add((Integer) questionIdObj);
        } else if (questionId instanceof List) {
            questionId = (List<Integer>) questionIdObj;
        }
        String questionLibId = (String) questionLibIdObj;

        ResultT resultT = questionService.deleteQuestion(questionId, questionLibId);
        return resultT;
    }

    @PostMapping("/update")
    @ApiOperation("修改题目")
    public ResultT update(@RequestBody UpdateQuestionVo updateQuestionVo) {
        Integer questionId = updateQuestionVo.getQuestionId();

        if (questionService.getById(questionId) == null) {
            return ResultT.fail("数据错误");
        }

        Question question = questionService.getById(questionId);
        question.setAnalyse(updateQuestionVo.getAnalyse());
        question.setAnswer(updateQuestionVo.getAnswer());
        question.setLibId(Integer.parseInt(updateQuestionVo.getLibId()));
        question.setOption(updateQuestionVo.getOption());
        question.setTitle(updateQuestionVo.getTitle());
        question.setType(updateQuestionVo.getType());


        boolean update = questionService.updateById(question);

        if (update) {
            return ResultT.success("操作成功");
        } else {
            return ResultT.fail("操作失败");
        }
    }

//    @GetMapping("/export")
//    @ApiOperation("导出题目")
//    public ResultT export(Integer questionLibId) {
//
//        LambdaQueryWrapper<Question> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(questionLibId != null, Question::getLibId, questionLibId);
//
//        List<Question> questionList = questionService.list(lqw);
//        ArrayList<ExportQuestionVo> exportQuestionVos = new ArrayList<>();
//
//        for (Question question : questionList) {
//            ExportQuestionVo exportQuestionVo = new ExportQuestionVo();
//            if (question.getType() == 0) {
//                exportQuestionVo.setType("单选题");
//            }
//            if (question.getType() == 1) {
//                exportQuestionVo.setType("多选题");
//            }
//            if (question.getType() == 2) {
//                exportQuestionVo.setType("判断题");
//            }
//            exportQuestionVo.setContent(question.getTitle());
//            exportQuestionVo.setAnswer(question.getAnswer());
//            exportQuestionVo.setAnalyse(question.getAnalyse());
//
//            exportQuestionVos.add(exportQuestionVo);
//        }
//        if (CollUtil.isNotEmpty(exportQuestionVos)) {
//            // 通过hutool工具类创建writer，默认创建xls格式
//            ExcelWriter writer = ExcelUtil.getWriter("D:\test\test.xls");
//            //将list map数据写出文件
//            writer.write(exportQuestionVos, true);
//            writer.close();
//            return ResultT.success();
//        } else {
//            return ResultT.fail("表无数据！");
//        }
//    }

//    @GetMapping("/export")
//    @ApiOperation("导出题目")
//    public ResultT export(Integer questionLibId) {
//
//        LambdaQueryWrapper<Question> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(questionLibId != null, Question::getLibId, questionLibId);
//
//        List<Question> questionList = questionService.list(lqw);
//        ArrayList<Map<String, Object>> exportQuestionVos = new ArrayList<>();
//
//        for (Question question : questionList) {
//            LinkedHashMap<String, Object> map = new LinkedHashMap<>();
//            if (question.getType() == 0) {
//                map.put("题型", "单选题");
//            }
//            if (question.getType() == 1) {
//                map.put("题型", "多选题");
//            }
//            if (question.getType() == 2) {
//                map.put("题型", "判断题");
//            }
//
//            map.put("题干内容", question.getTitle());
//            map.put("正确答案", question.getAnswer());
//            map.put("答案解析", question.getAnalyse());
//
//            exportQuestionVos.add(map);
//        }
//        if (CollUtil.isNotEmpty(exportQuestionVos)) {
//            ExcelWriter writer = ExcelUtil.getWriter("D:/exportDemo/test.xls");
//            writer.write(exportQuestionVos, true);
//            writer.close();
//
//            return ResultT.success("操作成功");
//        } else {
//            return ResultT.fail("操作失败");
//        }
//    }


    @GetMapping("/export")
    @ApiOperation("导出题目")
    public void export(Integer questionLibId, HttpServletResponse response) throws IOException {

        Questionlib questionlib = questionlibService.getById(questionLibId);

        LambdaQueryWrapper<Question> lqw = new LambdaQueryWrapper<>();
        lqw.eq(questionLibId != null, Question::getLibId, questionLibId);

        List<Question> questionList = questionService.list(lqw);
        List<Map<String, Object>> exportQuestionVos = new ArrayList<>();

        for (Question question : questionList) {
            LinkedHashMap<String, Object> map = new LinkedHashMap<>();
            if (question.getType() == 0) {
                map.put("题型", "单选题");
            }
            if (question.getType() == 1) {
                map.put("题型", "多选题");
            }
            if (question.getType() == 2) {
                map.put("题型", "判断题");
            }

            map.put("题干内容", question.getTitle());
            map.put("正确答案", question.getAnswer());
            map.put("答案解析", question.getAnalyse());

            List<String> optionSplit = StrUtil.split(question.getOption(), "&&");

            ArrayList<String> modelList = new ArrayList<>();
            modelList.add("选项A");
            modelList.add("选项B");
            modelList.add("选项C");
            modelList.add("选项D");
            modelList.add("选项E");
            modelList.add("选项F");

            for (int i = 0; i < optionSplit.size(); i++) {
                map.put(modelList.get(i), optionSplit.get(i));
            }
            exportQuestionVos.add(map);
        }
        if (CollUtil.isNotEmpty(exportQuestionVos)) {

            ExcelWriter writer = ExcelUtil.getWriter();
            exportQuestionVos.sort((m1, m2) -> Integer.valueOf(m2.size()).compareTo(Integer.valueOf(m1.size())));
            writer.write(exportQuestionVos, true);
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            String fileName = URLEncoder.encode(questionlib.getTitle() + ".xls", "UTF-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out);
            writer.close();
        }
    }

//    @GetMapping("/downloadTemplate")
//    @ApiOperation("下载模板")
//    public void downloadTemplate(@RequestBody HttpServletResponse response) throws FileNotFoundException {
//        String templateScource =
//    }

//    @GetMapping("downloadTemplate")
//    @ApiOperation("下载模板")
//    public void resourceDownload(String name, HttpServletRequest request, HttpServletResponse response) throws Exception
//    {
//        // 下载名称
//        String downloadName = System.getProperty("user.dir") + "/src/main/java/com/hzncc/scaffold/template/questionTemplate.xlsx";
//
//        response.setCharacterEncoding("utf-8");
//        response.setContentType("multipart/form-data");
//        response.setHeader("Content-Disposition",
//                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
//        FileUtils.writeBytes("D://", response.getOutputStream());
//    }

    @PostMapping("/import")
    @ApiOperation("导入题目")
    private ResultT readerExcelInfo(@RequestParam("file") MultipartFile file, Integer questionLibId) throws IOException {

        InputStream inputStream = file.getInputStream();

        try {
            ExcelReader excelReader = ExcelUtil.getReader(inputStream);
            excelReader.addHeaderAlias("题型", "type");
            excelReader.addHeaderAlias("题干内容", "content");
            excelReader.addHeaderAlias("答案解析", "analyse");
            excelReader.addHeaderAlias("正确答案", "answer");
            excelReader.addHeaderAlias("选项 A", "optionA");
            excelReader.addHeaderAlias("选项 B", "optionB");
            excelReader.addHeaderAlias("选项 C", "optionC");
            excelReader.addHeaderAlias("选项 D", "optionD");
            excelReader.addHeaderAlias("选项 E", "optionE");
            excelReader.addHeaderAlias("选项 F", "optionF");
            List<QuestionReaderBo> questionReaderBos = excelReader.readAll(QuestionReaderBo.class);

            for (QuestionReaderBo questionReaderBo : questionReaderBos) {
                Question question = new Question();
                question.setId(questionLibId);

                if ("单选题".equals(questionReaderBo.getType())) {
                    question.setType(0);
                }
                if ("多选题".equals(questionReaderBo.getType())) {
                    question.setType(1);
                }
                if ("判断题".equals(questionReaderBo.getType())) {
                    question.setType(2);
                }

                question.setTitle(questionReaderBo.getContent());
                question.setAnswer(questionReaderBo.getAnswer());
                question.setAnalyse(questionReaderBo.getAnalyse());

                String option = "";
                if (StrUtil.isNotEmpty(questionReaderBo.getOptionA())) {
                    option += questionReaderBo.getOptionA();
                    if (StrUtil.isNotEmpty(questionReaderBo.getOptionB())) {
                        option += "&&";
                    }
                }
                if (StrUtil.isNotEmpty(questionReaderBo.getOptionB())) {
                    option += questionReaderBo.getOptionB();
                    if (StrUtil.isNotEmpty(questionReaderBo.getOptionC())) {
                        option += "&&";
                    }
                }
                if (StrUtil.isNotEmpty(questionReaderBo.getOptionC())) {
                    option += questionReaderBo.getOptionC();
                    if (StrUtil.isNotEmpty(questionReaderBo.getOptionD())) {
                        option += "&&";
                    }
                }
                if (StrUtil.isNotEmpty(questionReaderBo.getOptionD())) {
                    option += questionReaderBo.getOptionD();
                    if (StrUtil.isNotEmpty(questionReaderBo.getOptionE())) {
                        option += "&&";
                    }
                }
                if (StrUtil.isNotEmpty(questionReaderBo.getOptionE())) {
                    option += questionReaderBo.getOptionE();
                    if (StrUtil.isNotEmpty(questionReaderBo.getOptionF())) {
                        option += "&&";
                    }
                }
                if (StrUtil.isNotEmpty(questionReaderBo.getOptionF())) {
                    option += questionReaderBo.getOptionF();
                }
                question.setOption(option);
                question.setLibId(questionLibId);

                questionService.save(question);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            return ResultT.fail("操作失败");
        }
        return ResultT.success("操作成功");
    }

    @GetMapping("/downloadTemplate")
    @ApiOperation("下载题库模板")
    public void downloadTemplate(HttpServletResponse response) throws FileNotFoundException {

//        String path = System.getProperty("user.dir") + "\\src\\main\\java\\com\\hzncc\\scaffold\\template\\" +"questionTemplate.xlsx";
//        String path = System.getProperty("user.dir") +"\\scaffold\\template\\questionTemplate.xlsx";
        String path = FileUtil.getUploadResource("questionTemplate.xlsx");

        try {
            // path是指想要下载的文件的路径
            File file = new File(path);
            // 获取文件名
            String filename = file.getName();
            // 获取文件后缀名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();

            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("题库模板.xlsx", "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Credentials", "true");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
